package com.sk.weichat.ui.contacts.label;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.Label;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.LabelDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.CircleImageView;
import com.sk.weichat.view.ClearEditText;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_DRAGGING;
import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static android.support.v7.widget.RecyclerView.SCROLL_STATE_SETTLING;


public class CreateLabelActivity2 extends EditBaseActivity implements View.OnClickListener {
    private SideBar mSideBar;
    TextView tvSlideDialog;
    TextView tvTipsLabelMembers;
    TextView tvFinish;
    EditText edtName;
    static final String LabelKey = "CreateLabelActivity2_LabelKey";
    static final String OriginalLabelsKey = "CreateLabelActivity2_originalLabels"; //标签列表
    private Label label;
    private RecyclerView recyclerView;
    List<BaseSortModel<Friend>> friendList = new ArrayList<>();
    private LabelAdapter adapter;

    private ArrayList<Label> originalLabels;
    private List<BaseSortModel<Friend>> originalFriendList = new ArrayList<>();
    private static final int request_add_member = 7561;

    public static void startCreateLabelActivity2ForResult(Activity activity, int requestCode, Label label, ArrayList<Label> originalLabels) {
        Intent intent = new Intent(activity, CreateLabelActivity2.class);
        intent.putExtra(LabelKey, label);
        intent.putParcelableArrayListExtra(OriginalLabelsKey, originalLabels);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_label2);
        label = getIntent() != null && getIntent().hasExtra(LabelKey) ? getIntent().getParcelableExtra(LabelKey) : null;
        originalLabels = getIntent() != null && getIntent().hasExtra(OriginalLabelsKey) ? getIntent().getParcelableArrayListExtra(OriginalLabelsKey) : null;
        initActionBar();
        initView();
        initData();
    }

    private void initData() {
        if (label != null) {
            Map<String, Integer> existMap = new HashMap<>();
            friendList.clear();
            List<String> list = JSON.parseArray(label.getUserIdList(), String.class);
            List<Friend> friends = new ArrayList<>();
            Observable.create(new ObservableOnSubscribe<List<BaseSortModel<Friend>>>() {

                @Override
                public void subscribe(ObservableEmitter<List<BaseSortModel<Friend>>> emitter) throws Exception {
                    if (list != null) {
                        for (String s : list) {
                            Friend friend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), s);
                            friends.add(friend);
                        }
                        List<BaseSortModel<Friend>> sortList = SortHelper.toSortedModelList(friends, existMap, Friend::getShowName);
                        emitter.onNext(sortList);
                    }
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<BaseSortModel<Friend>>>() {
                        @Override
                        public void accept(List<BaseSortModel<Friend>> sortModels) throws Exception {
                            if (sortModels != null) {
                                friendList.addAll(sortModels);
                                originalFriendList.addAll(sortModels);
                            }
                            mSideBar.setExistMap(existMap);
                            adapter.notifyDataSetChanged();
                            //设置标签成员数量
                            tvTipsLabelMembers.setText(getString(R.string.tag_member) + "(" + friendList.size() + ")");
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {

                        }
                    });
        }
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        TextView tvTitle = findViewById(R.id.tv_title_center);
        if (label != null) {
            tvTitle.setText(R.string.edit_tag);
        } else {
            tvTitle.setText(R.string.create_tag);
        }

        tvFinish = findViewById(R.id.tv_title_right);
        tvFinish.setOnClickListener(this);
        tvFinish.setText("完成");
    }

    /**
     * 判断是否存在重复的名字
     *
     * @param name
     * @return
     */
    private boolean checkName(String name) {
        boolean flag = false;
        if (originalLabels != null) {
            for (int i = 0; i < originalLabels.size(); i++) {
                String groupname = originalLabels.get(i).getGroupName().trim();
                if (!TextUtils.isEmpty(groupname) && groupname.equals(name)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * 检查是否修改过标签成员
     *
     * @return
     */
    private boolean checkUpdateFriend() {
        boolean flag = false;
        for (int i = 0; i < originalFriendList.size(); i++) {
            int id = originalFriendList.get(i).getBean().get_id();
            flag = true;
            for (int i1 = 0; i1 < friendList.size(); i1++) {
                if (friendList.get(i1).getBean().get_id() == id) {
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
        }
        return flag;
    }

    private void initView() {
        tvTipsLabelMembers = findViewById(R.id.tv_tips_label_members);
        edtName = findViewById(R.id.edt_name);
        //设置标签名称
        if (label != null) {
            edtName.setText(label.getGroupName());
        }
        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                adjust(s.toString().trim());
            }
        });

        findViewById(R.id.tv_add_member).setOnClickListener(this);
        //字母拖动条
        mSideBar = findViewById(R.id.slidebar);
        tvSlideDialog = findViewById(R.id.tv_dialog);
        mSideBar.setTextView(tvSlideDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    recyclerView.smoothScrollToPosition(position);
                    showTextDialog(s);
                }
            }
        });
        //列表
        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        //
        adapter = new LabelAdapter(R.layout.item_edit_label_friend, friendList);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_delete) {
                    //删除成员
                    if (friendList.size() == 1) {// 最后一个也被删除了
                        enableBtnFinish(false);
                    } else {
                        enableBtnFinish(true);
                    }
                    friendList.remove(position);
                    adapter.notifyDataSetChanged();
                    tvTipsLabelMembers.setText(getString(R.string.tag_member) + "(" + friendList.size() + ")");
                }
                if (view.getId() == R.id.content) {
                    //个人主页
                    BaseSortModel<Friend> friend = friendList.get(position);
                    if (friend != null) {
                        Intent intent = new Intent(CreateLabelActivity2.this, PersonalCenterActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getBean().getUserId());
                        startActivity(intent);
                    }
                }
            }
        });

        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int lvScrollPosition;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
                if (firstVisibleItemPosition < 0) {
                    return;
                }
                String firstLetter = friendList.get(firstVisibleItemPosition).getFirstLetter();
                if (firstLetter != null && !firstLetter.equals("")) {
                    mSideBar.searchByFirstStr(firstLetter);
                    if (firstVisibleItemPosition != 0) {
                        String strLast = friendList.get(firstVisibleItemPosition - 1).getFirstLetter();
                        String strSec = friendList.get(firstVisibleItemPosition + 1).getFirstLetter();
                        if (lvScrollPosition < firstVisibleItemPosition) {
                            if (!firstLetter.equals(strLast)) {
                                showTextDialog(firstLetter);
                            }
                        } else if (lvScrollPosition > firstVisibleItemPosition) {
                            if (!firstLetter.equals(strSec)) {
                                showTextDialog(firstLetter);
                            }
                        }
                    }
                }
                lvScrollPosition = firstVisibleItemPosition;
            }
        });
        adjust(edtName.getText().toString().trim());
    }

    private void showTextDialog(String s) {
        tvSlideDialog.setText(s);
        tvSlideDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    tvSlideDialog.startAnimation(aa);
                    tvSlideDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tv_title_right:
                //完成
                if (label != null) {
                    if (checkName(edtName.getText().toString().trim()) && !label.getGroupName().trim().equals(edtName.getText().toString().trim())) {
                        //判断是否重复
                        ToastUtil.showToast(mContext, "标签已存在");
                    } else {
                        if (!label.getGroupName().trim().equals(edtName.getText().toString().trim())) {
                            // 标签名已改变
                            updateLabelName();
                        }
                        updateLabelUserIdList(label);
                    }
                } else {
                    createLabel();
                }
                break;
            case R.id.tv_add_member:
                Intent intent = new Intent(this, SelectLabelFriendActivity.class);
                List<String> ids = new ArrayList<>();
                for (int i = 0; i < friendList.size(); i++) {
                    /*过滤悦聊团队id*/
                    if (!friendList.get(i).getBean().getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                        ids.add(friendList.get(i).getBean().getUserId());
                    }
                }
                intent.putExtra("exist_ids", JSON.toJSONString(ids));
                startActivityForResult(intent, request_add_member);
                break;

        }
    }

    // 创建标签
    private void createLabel() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        String groupName = AppUtils.replaceBlank(edtName.getText().toString().trim());

        params.put("groupName",groupName);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ObjectResult<Label> result) {
                        if (result.getResultCode() == 1) {
                            LabelDao.getInstance().createLabel(result.getData());
                            updateLabelUserIdList(result.getData());
                        } else {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (request_add_member == requestCode) {
                String userIds = data.getStringExtra("inviteId");
                String userNames = data.getStringExtra("inviteName");
                List<String> userIdList = JSON.parseArray(userIds, String.class);
                List<String> userNameList = JSON.parseArray(userNames, String.class);

                for (int i = 0; i < userIdList.size(); i++) {
                    Friend friend = new Friend();
                    friend.setUserId(userIdList.get(i));
                    friend.setNickName(userNameList.get(i));
                    BaseSortModel<Friend> friendBaseSortModel = new BaseSortModel<>();
                    friendBaseSortModel.setBean(friend);
                    SortHelper.setSortCondition(friendBaseSortModel, friend.getShowName());
                    friendList.add(friendBaseSortModel);
                    Collections.sort(friendList, SortHelper.getSortComparator());
                }
                Map<String, Integer> map = new HashMap<>();
                for (int i = 0; i < friendList.size(); i++) {
                    map.put(friendList.get(i).getFirstLetter(), i);
                }
                mSideBar.setExistMap(map);
                adapter.notifyDataSetChanged();
                if (friendList.size() > 0 && !TextUtils.isEmpty(edtName.getText().toString().trim())) {
                    //完成可点击
                    enableBtnFinish(true);
                } else {
                    //完成不可点击
                    enableBtnFinish(false);
                }
                tvTipsLabelMembers.setText(getString(R.string.tag_member) + "(" + friendList.size() + ")");
            }
        }
    }

    /**
     * 修改标签名称
     */
    private void updateLabelName() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("groupId", label.getGroupId());

        params.put("groupName", AppUtils.replaceBlank(edtName.getText().toString().trim()));

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_UPDATE)
                .params(params)
                .build()
                .execute(new BaseCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ObjectResult<Label> result) {
                        if (result.getResultCode() == 1) {
                            LabelDao.getInstance().updateLabelName(coreManager.getSelf().getUserId(), label.getGroupId(), edtName.getText().toString().trim());
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }

    // 修改标签下的成员
    private void updateLabelUserIdList(final Label label) {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("groupId", label.getGroupId());
        String userIdListStr = "";
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < friendList.size(); i++) {
            if (i == friendList.size() - 1) {
                userIdListStr += friendList.get(i).getBean().getUserId();
            } else {
                userIdListStr += friendList.get(i).getBean().getUserId() + ",";
            }
            strings.add(friendList.get(i).getBean().getUserId());
        }
        params.put("userIdListStr", userIdListStr);
        final String userIdList = JSON.toJSONString(strings);

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_UPDATEGROUPUSERLIST)
                .params(params)
                .build()
                .execute(new BaseCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ObjectResult<Label> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            LabelDao.getInstance().updateLabelUserIdList(coreManager.getSelf().getUserId(), label.getGroupId(), userIdList);
                            setResult(Activity.RESULT_OK);
                            finish();
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    /**
     * 判断是否可以创建标签
     */
    private void adjust(String labelName) {
        if (TextUtils.isEmpty(labelName) || friendList.size() == 0) {
            enableBtnFinish(false);
        } else {
            enableBtnFinish(true);
        }
    }

    private void enableBtnFinish(boolean enable) {
        if (enable) {
            tvFinish.setTextColor(getResources().getColor(R.color.colorPrimary));
            tvFinish.setEnabled(true);
        } else {
            tvFinish.setTextColor(getResources().getColor(R.color.text_color_content));
            tvFinish.setEnabled(false);
        }
    }

    class LabelAdapter extends BaseQuickAdapter<BaseSortModel<Friend>, BaseViewHolder> implements SectionIndexer {

        List<BaseSortModel<Friend>> data;


        public LabelAdapter(int layoutResId, @Nullable List<BaseSortModel<Friend>> data) {
            super(layoutResId, data);
            this.data = data;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

        @Override
        public int getPositionForSection(int sectionIndex) {
            for (int i = 0; i < data.size(); i++) {
                String sortStr = data.get(i).getFirstLetter();
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == sectionIndex) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public int getSectionForPosition(int position) {
            return data.get(position).getFirstLetter().charAt(0);
        }

        @Override
        protected void convert(BaseViewHolder holder, BaseSortModel<Friend> item) {
            holder.addOnClickListener(R.id.content, R.id.tv_delete);

            TextView tvLetter = holder.getView(R.id.tv_letter);
            int position = holder.getLayoutPosition();
            int section = getSectionForPosition(position);
            // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if (position == getPositionForSection(section)) {
                tvLetter.setVisibility(View.VISIBLE);
                tvLetter.setText(item.getFirstLetter());
            } else {
                tvLetter.setVisibility(View.GONE);
            }
            holder.setText(R.id.tv_name, item.getBean().getNickName());
            RoundedImageView circleImageView = holder.getView(R.id.iv_avatar);
            AvatarHelper.getInstance().displayAvatar(item.getBean().getUserId(), circleImageView);
        }
    }
}
